class HomeController < ApplicationController
  layout "home"
  
  def index
    if session[:user_name].nil?
      @page_title = "Microblog_Home"
    else
      users = User.find(:all, :conditions => ["name='#{session[:user_name]}'"])
      @user = users[0]
      @page_title = "Microblog_Welcome #{@user.display_name}!"
      @dm_count = DirectMessage.get_dm_count_by_id(@user.id)
      
      # Temporarily put the messages of oneself.
      # After the relationship implemented, All the friends messages will be here.
      
      # Copy from user controller
      @paged = false
      if session[:user_name].nil?
        redirect_to(:controller => :home, :action => "index")
      else
        users = User.find(:all, :conditions => ["name='#{session[:user_name]}'"])
        @user = users[0]
        get_paged_message(@user.id)
        
        # deal with requests
        @requester_ids = []
        
        if Request.request_count(@user.id)
          Request.request_list(@user.id).each do |r|
            @requester_ids << [r.id, r.requester_id]
          end
        end
        
        @notices = []
        
        if @requester_ids.size
          @requester_ids.each do |r|
            user = User.find(r[1])
            @notices << "<a href=\"/message/user/#{r[1]}\">#{user.display_name}</a> want to add you as a friend. <a href=\"/request/accept/#{r[0]}\">Accept</a>&nbsp;&nbsp;<a href=\"/request/ignore/#{r[0]}\">Ignore</a>"
          end
        end
        
        # end of deal with requests
      end
      
      # End of Copy

    end
  end
  
  # Copy from user controller
  private
  
  def get_message_count(id)
    #Message.find(:all, :conditions => ["user_id='#{id}'"]).length
    Message.find_by_sql("SELECT * FROM messages WHERE user_id=#{id} or user_id IN (SELECT user_id FROM followers WHERE follower_id=#{id})").length
  end
  
  def get_paged_message(id)
    @message_count = get_message_count(id)
    @page_count = (@message_count / 20.0).ceil
    if @message_count > 20
      @paged = true
    end
    @page = params[:page].nil? ? 1 : params[:page].to_i
    shift = (@page - 1) * 20
    @messages = Message.find_by_sql("SELECT * FROM messages WHERE user_id='#{id}' OR user_id IN (SELECT user_id FROM followers WHERE follower_id='#{id}') ORDER BY post_at DESC LIMIT 20 OFFSET #{shift}")
  end
  # End of Copy
  
  
end
